package com.demo.gulimall.ware.config;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.HashMap;

/**
 * @author Chen Yuan
 * @create 2023-07-03  15:28
 */
@Slf4j
@Configuration
public class MyRabbitMQConfig {

	// 监听队列
	//@RabbitListener(queues = {"stock.release.queue"})
	//public void queueListener(stock stock, Channel channel, Message message) throws IOException {
	//	String create = DateFormatUtils.format(stock.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
	//	String now = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	//	log.info("==> queueListener - 接收到订单信息 - 准备关闭订单 - stockSn:{}, create:{}, now:{}", stock.getstockSn(), create, now);
	//
	//	// 手动确认消息
	//	channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	//}


	// 创建延迟队列
	@Bean
	public Queue stockDelayQueue(){
		// 自定义的属性
		HashMap<String, Object> arguments = new HashMap<>();
		arguments.put("x-dead-letter-exchange", "stock-event-exchange");
		arguments.put("x-dead-letter-routing-key", "stock.release");
		arguments.put("x-message-ttl", 120*1000);

		// 参数: 名称, 是否持久化, 是否排他的(只要有连接正在使用, 其他连接就不能使用), 是否自动删除, 自定义的属性
		return new Queue("stock.delay.queue", true, false, false, arguments);
	}

	// 创建死信队列
	@Bean
	public Queue stockReleaseQueue(){
		return new Queue("stock.release.queue", true, false, false);
	}

	// 创建死信交换机
	@Bean
	public Exchange stockEventExchange(){

		return new TopicExchange("stock-event-exchange", true, false);
	}

	// 创建订单时的绑定关系
	@Bean
	public Binding stockCreateBinding(){
		return new Binding("stock.delay.queue", Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.locked", null);
	}

	// 创建死信绑定关系
	@Bean
	public Binding stockReleaseBinding(){
		return new Binding("stock.release.queue", Binding.DestinationType.QUEUE, "stock-event-exchange", "stock.release.#", null);
	}
}
